﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ERF;
using FirstPerson.Objects;
using FirstPerson;
using Microsoft.Xna.Framework;
using FirstPerson.States;

namespace FirstPerson.Gametypes
{
    public class DeathMatch : GameType
    {
        private int killLimit = 0;

        public int KillLimit
        {
            get { return killLimit; }
            set { killLimit = value; }
        }


        public DeathMatch(ERFGame game)
            : base(game)
        {
            ((FirstPerson.PlayerHandler)this.game.PlayerHandler).PlayerKill += new EventHandler<PlayerKillEventArgs>(DeathMatch_PlayerKill);
            ((FirstPerson.PlayerHandler)this.game.PlayerHandler).PlayerDie += new EventHandler<PlayerDieEventArgs>(DeathMatch_PlayerDie);
        }

        void DeathMatch_PlayerDie(object sender, PlayerDieEventArgs e)
        {
            e.Victim.Deaths++;
            if (!e.Victim.Equals(e.Killer))
                e.Killer.Kills++;
            ResetPlayer(e.Victim);
        }

        void DeathMatch_PlayerKill(object sender, PlayerKillEventArgs e)
        {
            e.Victim.Deaths++;
            e.Killer.Kills++;
        }

        public override bool IsGameOver(GameTime gameTime)
        {
            if (gameTime.TotalRealTime - StartTime >= new TimeSpan(0, 0, DurationTime))
                return true;

            List<Player> players = ((FirstPerson.PlayerHandler) game.PlayerHandler).PlayersList;

            foreach (Player player in players)
            {
                if (killLimit == Score(player))
                    return true;
            }

            return false;
        }

        public override int Score(FirstPerson.Objects.Player player)
        {
            return player.Kills - player.Deaths;
        }

        public override Vector3 PickSpawnpointPosition()
        {
            Vector2 pos = this.PickRandomSpawnPoint().Position;
            
            float height = PlayingState.GetInstance(this.game.StateMachine).GameWorld.GetHeightFromXZ(pos.X, pos.Y);

            return new Vector3(pos.X, height, pos.Y);
        }
    }
}
